/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.util.xml;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Alejandro Riveros Cruz Riveros Cruz
 */
public class XMLDOM {

    /**
     * 
     */
    public XMLDOM() {
    }

    /**
     * 
     * @param filePath
     * @return
     */
    public TableDocument parseSingleDocument(String filePath) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(filePath);
            TableDocument tableDocument = new TableDocument(new String(filePath.substring(filePath.lastIndexOf(File.separator) + 1, filePath.length())));
            Element documentElement = document.getDocumentElement();
            NodeList nodeList = documentElement.getElementsByTagName("*");
            if (nodeList != null) {
                for (int i = 0; i < nodeList.getLength(); i++) {
                    tableDocument.addTagContent(nodeList.item(i).getNodeName(), nodeList.item(i).getTextContent());
                }
            }
            return tableDocument;
        } catch (ParserConfigurationException pce) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, "Error while parsing XML file", pce);
        } catch (SAXException saxe) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, "Error while parsing XML file", saxe);
        } catch (IOException ioe) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, "Error while parsing XML file", ioe);
        }
        return null;
    }

    /**
     * 
     * @param filePath
     * @param splitNodeName
     * @return
     * @deprecated
     */
    @Deprecated
    public List<TableDocument> parseMultipleDocumentsByNode(String filePath, String splitNodeName) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(filePath);
            List<TableDocument> XMLDocumentList = new ArrayList<TableDocument>();
            Element documentElement = document.getDocumentElement();
            NodeList nodeList = documentElement.getElementsByTagName(splitNodeName);
            NodeList childNodes;
            TableDocument tableDocument;
            for (int i = 0; i < nodeList.getLength(); i++) {
                tableDocument = new TableDocument();
                childNodes = nodeList.item(i).getChildNodes();
                if (childNodes != null && childNodes.getLength() > 0) {
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        tableDocument.addTagContent(childNodes.item(j).getNodeName(), childNodes.item(j).getTextContent());
                    }
                }
                XMLDocumentList.add(tableDocument);
            }
            return XMLDocumentList;
        } catch (ParserConfigurationException pce) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, "Error while parsing PDF file" , pce);
        } catch (SAXException se) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, "Error while parsing PDF file" , se);
        } catch (IOException ioe) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, "Error while parsing PDF file" , ioe);
        }
        return null;
    }

    /**
     * 
     * @param path
     * @param tableDocument
     */
    public static void saveXMLFile(String path, TableDocument tableDocument) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            String currentKey;
            Element element = document.createElement(tableDocument.getName());
            Element subElement;
            for (Enumeration<String> keys = tableDocument.getContent().keys(); keys.hasMoreElements();) {
                currentKey = keys.nextElement();
                subElement = document.createElement(currentKey);
                subElement.setTextContent(tableDocument.getTagContent(currentKey));
                element.appendChild(subElement);
            }
            document.appendChild(element);
            Source source = new DOMSource(document);
            Result result = new StreamResult(new File(path + tableDocument.getTagContent("case_id") + ".xml").toURI().getPath());
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(source, result);
        } catch (ParserConfigurationException pce) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, null, pce);
        } catch (TransformerConfigurationException tce) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, null, tce);
        } catch (TransformerException te) {
            Logger.getLogger(XMLDOM.class.getName()).log(Level.SEVERE, null, te);
        }
    }

    /**
     * 
     * @param document
     * @param element
     * @param node
     */
    public static void convertToDOMXML(Document document, Element element, NodeXML node) {
        Element subElement;
        if (!node.isLeaf()) {
            List<NodeXML> childs = node.getChilds();
            for (NodeXML current : childs) {
                try {
                    subElement = document.createElement(current.getName());
                    if (current.getValue() != null) {
                        subElement.setTextContent(current.getValue());
                    }
                    element.appendChild(subElement);
                    convertToDOMXML(document, subElement, current);
                } catch (org.w3c.dom.DOMException dome) {
                    System.out.println(current.getName());
                }
            }
        }
    }
}
